package mvc;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;
import org.primefaces.model.UploadedFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author tadiwa
 */
@ManagedBean(name = "fileUploadController")
public class FileUploadController {

    public FileUploadController() {
    }
    private String destination = "/home/tadiwa/Uploads/";
    private UploadedFile file;
    private static final Logger log = LoggerFactory.getLogger(FileUploadController.class);

    public UploadedFile getFile() {
        return file;
    }

    public void setFile(UploadedFile file) {
        this.file = file;
    }

    public void Transferfile(String fileName, InputStream in) {
        try {
            OutputStream out = new FileOutputStream(new File(destination + fileName));
            int reader = 0;
            byte[] bytes = new byte[(int) getFile().getSize()];
            while ((reader = in.read(bytes)) != -1) {
                out.write(bytes, 0, reader);
            }
            in.close();
            out.flush();
            out.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    public void upload() throws IOException {
        String extValidate = null;
        if (getFile() != null) {
            String ext = getFile().getFileName();
            if (ext != null) {
                extValidate = ext.substring(ext.indexOf(".") + 1);
            } else {
                extValidate = "null";
            }

            if (extValidate.equals("pdf") || (extValidate.equals("doc")) || (extValidate.equals("docx")) | (extValidate.equals("ppt")) | (extValidate.equals("xls")) | (extValidate.equals("mkv")) | (extValidate.equals("xlsx")) | (extValidate.equals("csv"))) {
                try {
                    Transferfile(getFile().getFileName(), getFile().getInputstream());
                } catch (IOException ex) {
                    log.error(ex.getMessage(), ex);
                    FacesContext context = FacesContext.getCurrentInstance();
                    context.addMessage(null, new FacesMessage("Error: ", "Upload Failed"));
                }
                FacesContext context = FacesContext.getCurrentInstance();
                context.addMessage(null, new FacesMessage("Successfully uploaded", getFile().getFileName()));
            } else {
                FacesContext context = FacesContext.getCurrentInstance();
                context.addMessage(null, new FacesMessage("Error:", "Unsupported Format, use .pdf or .doc"));
            }
        } else {
            FacesContext context = FacesContext.getCurrentInstance();
            context.addMessage(null, new FacesMessage("Error:", "No Selected File"));
        }
    }

    public String getCurrentDate() {
        String dateString = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        Date date = calendar.getTime();
        dateString = sdf.format(date);
        return dateString;
    }

    public void downloadDoc() {
        try {
            File file = new File("/home/tadiwa/Uploads/" + getFile().getFileName());
            InputStream fis = new FileInputStream(file);
            byte[] buf = new byte[(int) (getFile().getSize())];
            int offset = 0;
            int numRead = 0;
            while ((offset < buf.length) && ((numRead = fis.read(buf, offset, buf.length - offset)) >= 0)) {

                offset += numRead;

            }
            fis.close();
            HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + getFile().getFileName() + "");
            response.getOutputStream().write(buf);
            response.getOutputStream().flush();
            response.getOutputStream().close();
            FacesContext.getCurrentInstance().responseComplete();
        } catch (IOException ex) {
            FacesContext context = FacesContext.getCurrentInstance();
            context.addMessage(null, new FacesMessage("Error:", "No File to download"));
        }
    }
}
